﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Municipios;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Modulos
{
	public partial class ModulosViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Municipio> _municipiosModulo;

		/// <summary>
		/// 
		/// </summary>
		private Municipio _municipioModulo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Municipio> MunicipiosModulo
		{
			get
			{
				return _municipiosModulo;
			}
			private set
			{
				_municipiosModulo = value;
				if (_municipiosModulo != null)
					RaisePropertyChanged("MunicipiosModulo");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Municipio MunicipioModulo
		{
			get
			{
				return _municipioModulo;
			}
			private set
			{
				_municipioModulo = value;
				if (_municipioModulo != null)
					RaisePropertyChanged("MunicipioModulo");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadMunicipiosModulo()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IMunicipioService service = IoCFactory.Resolve<IMunicipioService>();
					e.Result = service.FindMunicipiosByEstado(EstadoModulo.EstadoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						MunicipiosModulo = e.Result as List<Municipio>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentMunicipioModulo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				MunicipioModulo = bindingSource.Current as Municipio;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnMunicipiosModuloPropertyChanged()
		{
			_view.municipioBindingSource.DataSource = MunicipiosModulo;
			_view.municipioBindingSource.CurrentChanged += SetCurrentMunicipioModulo;
			SetCurrentMunicipioModulo(_view.municipioBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnMunicipioModuloPropertyChanged()
		{
		}

		#endregion

	}
}
